package org.ntu.rtsearch.store;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

/**
 * @author fuhao(email: hfhimage@gmail.com)         
 * @date 2011-7-21
 */
public class FSOutputStream extends OutputStream {

	private RandomAccessFile file = null;
	
	private volatile boolean isOpen;	// for not close twice
	
	public FSOutputStream(String path) throws FileNotFoundException {
		file = new RandomAccessFile(path, "rw");
		isOpen = true;
	}
	
	@Override
	protected void flushBuffer(byte[] b, int offset, int len) throws IOException {
		file.write(b, offset, len);
	}

	@Override
	protected long length() throws IOException {
		return file.length();
	}
	
	public final void close() throws IOException {
		if(isOpen) {
			super.close();
			file.close();
			isOpen = false;
		}
	}
	
	public final void seek(long pos) throws IOException {
		super.seek(pos);
		file.seek(pos);
	}
	
	protected final void finalize() throws IOException {
		file.close();
	}

}
